<template>
  <div class="submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img"></span>
          <span class="text">{{$t('submitOrder.submitOrder')}}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">step 01.</div>
            <div class="text">{{$t('submitOrder.selectProductToBuy')}}</div>
          </div>
          <div class="item active">
            <div class="number">step 02.</div>
            <div class="text">{{$t('submitOrder.confirmOrderInformation')}}</div>
          </div>
          <div class="item">
            <div class="number">step 03.</div>
            <div class="text">{{$t('submitOrder.payToCompleteTheOrder')}}</div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <!-- 收货地址 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('address.receivingAddress')}}</span>
            <!-- <span class="action">显示全部地址</span> -->
          </div>
          <div class="con address-box">
            <div
              :class="['item', address.commonAddr?'default-address':'',selectedAddrId==address.addrId?'active':'']"
              v-for="address in addressList"
              :key="address.addrId"
              @click="changeAddress(address.addrId)"
            >
              <div class="name-phone">
                <span class="name">{{address.receiver}}</span>
                <span class="phone">{{address.mobile}}</span>
                <span
                  class="set-default"
                  v-if="!address.commonAddr"
                  @click="setDefaultAddr(address.addrId)"
                >{{$t('address.setDefault')}}</span>
                <span class="default-tag" v-if="address.commonAddr">{{$t('address.default')}}</span>
              </div>
              <div
                class="address-detail"
              >{{address.province+address.city+address.area+address.addr}}</div>
              <div class="del-edit">
                <span class="edit" @click.stop="editAddr(address.addrId)"></span>
                <span class="del" @click.stop="toggleDelAddr(true,address.addrId)"></span>
              </div>
            </div>
            <div
              class="item add-address"
              @click="toggleAddrPop(true)"
              v-if="addressList.length < 10"
            >
              <div class="add-box">
                <div class="img">+</div>
                <div class="text">{{$t('address.addAddress')}}</div>
              </div>
            </div>
          </div>
          <div class="popup-mask" v-if="showDelAddr"></div>
          <div class="fix-transform-blur">
            <div class="popup-box" v-if="showDelAddr">
              <div class="tit" style="padding:10px;">
                <div class="text">{{$t('tips')}}</div>
                <div class="close" @click="toggleDelAddr(false)"></div>
              </div>
              <div class="con">
                <div class="tip">
                  <div class="tip-icon warning"></div>
                  <div class="tip-info">
                    <div class="result">{{$t('address.deleteShippingAddress')}}</div>
                    <div class="date">{{$t('address.deleteShippingTips')}}</div>
                    <div class="btns">
                      <a href="javascript:void(0);" @click="delAddr()" class="btn-r">{{$t('submitOrder.delete')}}</a>
                      <a href="javascript:void(0);" @click="toggleDelAddr(flase)" class="btn-g">{{$t('submitOrder.cancel')}}</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收货地址 -->
        <!-- 支付方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('commonFoot.paymentMethod')}}</span>
          </div>
          <div class="con pay-way">
            <div class="item active">{{$t('submitOrder.payOnline')}}</div>
            <!-- <div class="item">货到付款</div>
            <div class="item">线下支付</div>-->
          </div>
        </div>
        <!-- 支付方式 -->
        <!-- 配送方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('submitOrder.deliveryMethod')}}</span>
          </div>
          <div class="con delivery-way">
            <div class="item active">{{$t('submitOrder.courierDelivery')}}</div>
            <!-- <div class="item">到店自提</div> -->
            <!-- <div class="description">（该商品不支持自提）</div> -->
          </div>
        </div>
        <!-- /配送方式 -->
        <!-- 商品信息 -->
        <div class="submit-box goods-info">
          <div class="tit">
            <span class="text">{{$t('applyReturn.productInformation')}}</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">&nbsp;</div>
              <div class="info">{{$t('product')}}</div>
              <div class="unit-price">{{$t('priceOne')}}</div>
              <div class="freight">{{$t('submitOrder.shippingFee')}}</div>
              <div class="number">{{$t('quantity')}}</div>
              <div class="total">{{$t('subtotal')}}</div>
            </div>
            <div class="msg-con">
              <!-- 店铺 -->
              <!-- <div class="shop-msg">
                店铺：
                <a :href="'/shopIndex?sid='+shopCart.shopId"
                   class="shop-name">{{shopCart.shopName}}</a>
                <span class="self"
                      v-if="shopCart.shopId==1">自营</span>
              </div>-->
              <!-- 店铺中的商品 -->

              <div class="goods-box">
                <div class="img">
                  <a :href="'/detail/'+shopCartItem.prodId" class="img-box">
                    <img :src="shopCartItem.pic" alt />
                  </a>
                </div>
                <div class="info">
                  <a :href="'/detail/'+shopCartItem.prodId" class="name">{{shopCartItem.prodName}}</a>
                  <span class="sku">{{shopCartItem.skuName}}</span>
                </div>
                <div
                  class="unit-price"
                >￥{{parsePrice(shopCartItem.price)[0]}}.{{parsePrice(shopCartItem.price)[1]}}</div>
                <div
                  class="freight"
                >￥{{parsePrice(orderInfo.transfee)[0]}}.{{parsePrice(orderInfo.transfee)[1]}}</div>
                <div class="number">{{shopCartItem.prodCount}}</div>
                <div
                  class="total"
                >￥{{parsePrice(shopCartItem.productTotalAmount)[0]}}.{{parsePrice(shopCartItem.productTotalAmount)[1]}}</div>
              </div>
              <!-- 留言 -->
              <div class="remake-box">
                {{$t('submitOrder.messageToMerchant')}}：
                <input type="text" maxlength="100" class="text" v-model="remarks" :placeholder="$t('submitOrder.numberLength100')" />
              </div>
              <!-- /留言 -->
            </div>
          </div>
        </div>
      </div>
      <div class="submit-bottom">
        <div class="statistic-box">
          <div class="item">
            <div class="tit">
              <span class="number">{{orderInfo.totalCount}}</span>{{$t('submitOrder.totalItems')}}：
            </div>
            <div class="con">￥{{parsePrice(orderInfo.total)[0]}}.{{parsePrice(orderInfo.total)[1]}}</div>
          </div>
          <div class="item">
            <div class="tit">{{$t('submitOrder.freightPayable')}}：</div>
            <div
              class="con"
            >+￥{{parsePrice(orderInfo.transfee)[0]}}.{{parsePrice(orderInfo.transfee)[1]}}</div>
          </div>
          <div class="item">
            <div class="tit">{{$t('submitOrder.offerAmount')}}：</div>
            <div
              class="con"
            >-￥{{parsePrice(orderInfo.orderReduce)[0]}}.{{parsePrice(orderInfo.orderReduce)[1]}}</div>
          </div>
        </div>

        <div class="detail-box">
          <div class="item">
            <div class="tit">{{$t('submitOrder.totalPayable')}}：</div>
            <div
              class="con"
            >￥{{parsePrice(orderInfo.actualTotal)[0]}}.{{parsePrice(orderInfo.actualTotal)[1]}}</div>
          </div>
          <div class="item" v-if="currentAddr.addrId">
            <span
              class="text"
            >{{$t('submitOrder.sendTo')}}：{{currentAddr.province+' '+currentAddr.city +' '+currentAddr.area+' '+currentAddr.addr}}</span>
            <span class="text">{{$t('submitOrder.consignee')}}：{{currentAddr.receiver}} {{currentAddr.mobile}}</span>
          </div>
        </div>
        <div class="btn-box">
          <a href="javascript:void(0)" class="btn" @click="submitOrder">{{$t('submitOrder.submitOrder')}}</a>
        </div>
      </div>
    </div>
    <!-- 地址弹窗 -->
    <AddressPop
      :editAddrId="editAddrId"
      v-if="showAddrPop"
      @getAddrList="getAddrList"
      @toggleAddrPop="toggleAddrPop"
    />
    <!-- /地址弹窗 -->
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import bus from '~/plugins/bus'
import AddressPop from '~/components/add-or-edit-address'

export default {
  components: {
    AddressPop,
  },
  data () {
    return {
      addressList: [],
      selectedAddrId: 0,
      orderInfo: {},
      shopCartItem: {},
      currentAddr: {}, // 当前选择的地址
      showAddrPop: false, // 地址弹窗显隐
      editAddrId: 0, // 要修改的地址id
      showDelAddr: false,

      orderPath: '', // 秒杀订单路径
      secKillObj: {}, // 秒杀订单数据

      remarks: '',
      loading: {},
      seckillOrderNumber: '',
      pollingTimes: 0,
      seckillOrderStsTimer: '',
    }
  },
  created () {
    this.getAddrList()
  },
  mounted () {
    this.secKillObj = JSON.parse(sessionStorage.getItem('secKillObj'))
    this.getSecOrderPath()
  },
  methods: {

    /**
     * 获取地址列表
     */
    getAddrList () {
      this.$axios.get('/p/address/list').then(({ data }) => {
        this.addressList = data
      })
      if (this.orderPath && (this.selectedAddrId || this.selectedAddrId==0)) {
        this.confirmSecOrder(this.orderPath)
      }
    },

    /**
     * 选择地址
     */
    changeAddress (addrId) {
      this.addressList.forEach(element => {
        if (element.addrId == addrId) {
          this.currentAddr = element
        }
      });
      this.selectedAddrId = addrId
      this.confirmSecOrder(this.orderPath)
    },

    /**
     * 设置为默认地址
     */
    setDefaultAddr (addrId) {
      this.$axios.put('/p/address/defaultAddr/' + addrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.getAddrList()
      })
    },
    /**
     * 显示/隐藏确认删除弹窗
     */
    toggleDelAddr (sts, addrId) {
      this.showDelAddr = sts
      this.editAddrId = addrId
    },
    /**
     * 显示/隐藏地址弹窗
     */
    toggleAddrPop (sts) {
      if (Cookie.get('token')) {
        this.showAddrPop = sts
        this.editAddrId = 0
      } else {
        bus.$emit("showLogin", true)
        this.showAddrPop = false
      }
    },

    /**
     * 修改地址 (弹窗传地址id)
     */
    editAddr (addrId) {
      if (Cookie.get('token')) {
        this.showAddrPop = true
        this.editAddrId = addrId
      } else {
        bus.$emit("showLogin", true)
        this.showAddrPop = false
      }
    },
    /**
     * 删除地址
     */
    delAddr () {
      if (this.editAddrId == this.selectedAddrId) {
        this.secKillObj.addrId = 0
        this.selectedAddrId = 0
      }
      this.$axios.delete('/p/address/deleteAddr/' + this.editAddrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.toggleDelAddr(false)
        this.getAddrList()
      })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },


    /**  
     * 获取 orderPath 
     */
    getSecOrderPath () {
      this.$axios.get('/p/seckill/orderPath').then(({ data }) => {
        this.orderPath = data
        this.confirmSecOrder(data)
      })
    },

    /**
     * 确认秒杀订单
     */
    confirmSecOrder (orderPath) {
      var confirmParam = this.secKillObj
      if (this.selectedAddrId || this.selectedAddrId == 0) {
        confirmParam.addrId = this.selectedAddrId
      }
      this.$axios.post(`/p/seckill/${orderPath}/confirm`, confirmParam).then(({ data }) => {
        this.orderInfo = data
        this.shopCartItem = data.shopCartItem
        if (data.userAddr) {
          this.currentAddr = data.userAddr
          this.selectedAddrId = data.userAddr.addrId
        }
      })
    },

    /**
     * 提交订单
     */
    submitOrder () {
      if (!this.addressList.length) {
        this.$message({
          message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
          type: 'success',
          duration: 1000
        })
        this.showAddrPop = true
        return
      }
      if (this.selectedAddrId == 0) {
        this.$message({
          message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
          type: 'success',
          duration: 1000
        })
        document.body.scrollTop = document.documentElement.scrollTop = 0
        return
      }
      // 显示秒杀loading
      this.seckillLoading()
      // 提交秒杀订单
      var orderShopParam = {
        remarks: this.remarks,
        shopId: this.shopCartItem.shopId
      }
      this.$axios.post(`/p/seckill/${this.orderPath}/submit`, {
        orderShopParam: orderShopParam,
        orderPath: this.orderPath
      }).then(({data})=> {
        this.seckillOrderNumber = data.orderNumbers
        // 轮询秒杀订单提交状态
        setTimeout(this.checkSeckillOrderSubmitStatus,3000)
      }).catch(() => {
        // 关闭秒杀loading
        this.loading.close();
      })
    },

    /**
     *  轮询秒杀订单提交状态
     */
    checkSeckillOrderSubmitStatus() {
      if (this.pollingTimes < 10) {
        this.$axios.get('/p/seckill/createOrderStatus',  {   
          params : {
            orderNumber: this.seckillOrderNumber
          }
        }).then(({ data }) => {
          if (data) {
            clearTimeout(this.seckillOrderStsTimer)
            this.loading.close()
            sessionStorage.setItem("pay_total", this.shopCartItem.actualTotal)
            sessionStorage.setItem("pay_orderNumber", this.seckillOrderNumber)
            this.$router.push({
              path: '/payment'
            })
          } else {
            this.pollingTimes++
            this.seckillOrderStsTimer = setTimeout(this.checkSeckillOrderSubmitStatus, 3000)
          }
        })
      } else {
        this.loading.close()
        this.$message.warning(this.$t('submitOrder.secFailTips'))
      }
    },


    /**
     * 秒杀loading
     */
    seckillLoading () {
      const loading = this.$loading({
        lock: true,
        text: this.$t('submitOrder.inTheMadRushToBuy'),
        background: 'rgba(255, 255, 255, 0.8)'
      });
      this.loading = loading

    },
  },

}
</script>

<style scoped src='~/assets/css/submit-order.css'></style>
<style scoped>
.fix-transform-blur {
  z-index: 10000;
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
}
.seckill-loading {
  color: #fff;
}
</style>